#!/bin/bash
export HOMEDIR=$(dirname $(dirname $(readlink -f "${BASH_SOURCE[0]}")))
source $HOMEDIR/scripts/init-env.sh
schema_list=($(jq -r '.object.schemas[]' $HOMEDIR/config/mtk-config.json))

printf -v schema_string1 "'%s'," "${schema_list[@]}"
schema_string1=${schema_string1%,}

metadata_sql="
 select object_type, count(1) ct
    from dba_objects h
   where h.OWNER in ($schema_string1)
     and object_type in ('FUNCTION',
                         'INDEX',
                         'PACKAGE',
                         'PACKAGE BODY',
                         'PROCEDURE',
                         'SEQUENCE',
                         'TABLE',
                         'TYPE',
                         'TYPE BODY',
                         'VIEW',
                         'LARGE SEQUENCE')
     AND h.OBJECT_NAME NOT LIKE 'SYS\_%' ESCAPE '\'
   group by object_type
   order by 1;
"
metadata_dtl_sql="
 select object_type,owner, object_name
    from dba_objects h
   where h.OWNER in ($schema_string1)
     and object_type in ('FUNCTION',
                         'INDEX',
                         'PACKAGE',
                         'PACKAGE BODY',
                         'PROCEDURE',
                         'SEQUENCE',
                         'TABLE',
                         'TYPE',
                         'TYPE BODY',
                         'VIEW',
                         'LARGE SEQUENCE')
     AND h.OBJECT_NAME NOT LIKE 'SYS\_%' ESCAPE '\'
   order by 1,2,3;
"

echo 源端对象类型个数统计
$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --source -C "$metadata_sql"

echo 目标端对象类型个数统计
$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --target -C "$metadata_sql"

$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --source -C "$metadata_sql" -o source_metadata.csv --csv
$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --target -C "$metadata_sql" -o target_metadata.csv --csv
sed -i '1d' source_metadata.csv
sed -i '1d' target_metadata.csv

diff_output=$(diff target_metadata.csv source_metadata.csv -y --suppress-common-lines) || true
if [ -z "$diff_output" ]
then
  echo "对象个数核对无差异"
else
  echo "对象个数核对存在差异"
  echo "$diff_output"
fi

$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --source -C "$metadata_dtl_sql" -o source_metadata_dtl.csv --csv
$HOMEDIR/workspace/mtk/mtk -c $HOMEDIR/config/mtk-config.json usql --target -C "$metadata_dtl_sql" -o target_metadata_dtl.csv --csv
sed -i '1d' source_metadata_dtl.csv
sed -i '1d' target_metadata_dtl.csv

diff_output=$(diff target_metadata_dtl.csv source_metadata_dtl.csv -y --suppress-common-lines) || true
if [ -z "$diff_output" ]
then
  echo "按对象名称核对无差异"
else
  echo "按对象名称核对存在差异"
  echo "索引及约束存在部分重命名属正常情况"
  echo "$diff_output"
fi

echo 元数据检查完成